package br.com.rafsoft.mapaentrega.client;

import java.util.Date;

import br.com.rafsoft.mapaentrega.shared.MapaEntregaRequestFactory;
import br.com.rafsoft.mapaentrega.shared.MessageProxy;
import br.com.rafsoft.mapaentrega.shared.MessageRequest;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.InputElement;
import com.google.gwt.dom.client.TextAreaElement;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
import com.google.web.bindery.event.shared.EventBus;
import com.google.web.bindery.event.shared.SimpleEventBus;
import com.google.web.bindery.requestfactory.shared.Receiver;

public class MessageWidget extends Composite {

	private static MessageWidgetUiBinder uiBinder = GWT
			.create(MessageWidgetUiBinder.class);
	private final MapaEntregaRequestFactory requestFactory = GWT
			.create(MapaEntregaRequestFactory.class);
	private final EventBus eventBus = new SimpleEventBus();

	@UiField
	TextAreaElement textAreaText;

	@UiField
	InputElement textBoxUser;
	
	@UiField
	InputElement textBoxUserFrom;
	
	interface MessageWidgetUiBinder extends UiBinder<Widget, MessageWidget> {
	}

	public MessageWidget() {
		initWidget(uiBinder.createAndBindUi(this));
		requestFactory.initialize(eventBus);
	}

	@UiHandler("createUserButton")
	void onCreateUserButtonClick(ClickEvent event) {
		MessageRequest request = requestFactory.messageRequest();
		MessageProxy message = request.create(MessageProxy.class);
		message.setUserFrom(textBoxUserFrom.getValue());
		message.setUserTo(textBoxUser.getValue());		
		message.setText(textAreaText.getValue());
		message.setDate(new Date());

		request.updateMessage(message).fire(new Receiver<MessageProxy>() {

			@Override
			public void onSuccess(MessageProxy message) {
				Window.alert("CREATE SUCCESS: "+message.getId());				
			}
		});
	}
}
